/**
 * pagination - jQuery xui
 *
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2013 xjb [ beymy.en@gmail.com ]
 *
 * 依赖
 *   linkbutton
 */
(function($) {
    /**
     * 构建分页工具栏
     */
    function buildPagination(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target).addClass('x-pagination').empty();

        var pagination = ['<table cellspacing="0" cellpadding="0" border="0"><tr>']; //用table解决居中对齐问题
        if (opts.showPageList) {
            pagination.push('<td><select class="x-pagination-page-list">');
            for (var i = 0; i < opts.pageList.length; i++) {
                if (opts.pageSize == opts.pageList[i]) {
                    pagination.push('<option selected>' + opts.pageList[i] + '</option>');
                } else {
                    pagination.push('<option>' + opts.pageList[i] + '</option>');
                }
            }
            pagination.push('</select></td>');
            pagination.push('<td><div class="x-pagination-btn-separator"></div></td>');
        }
        pagination.push('<td><a class="x-pagination-first" href="javascript:void(0)">首&nbsp;页</a></td>');
        pagination.push('<td><a class="x-pagination-prev" href="javascript:void(0)">上一页</a></td>');
        pagination.push('<td><div class="x-pagination-btn-separator"></div></td>');
        pagination.push('<td><span class="x-pagination-before-page">第</span></td><td><input class="x-pagination-num" type="text" value="1"></td><td><span class="x-pagination-after-page">共{pages}页</span></td>');
        pagination.push('<td><div class="x-pagination-btn-separator"></div></td>');
        pagination.push('<td><a class="x-pagination-next" href="javascript:void(0)">下一页</a></td>');
        pagination.push('<td><a class="x-pagination-last" href="javascript:void(0)">末&nbsp;页</a></td>');
        if (opts.showRefresh) {
            pagination.push('<td><div class="x-pagination-btn-separator"></div></td>');
            pagination.push('<td><a class="x-pagination-reload" href="javascript:void(0)">刷新</a></td>');
        }
        pagination.push('</tr></table>');
        pagination.push('<span class="x-pagination-info">共{total}条记录</span>');
        pagination.push('<div style="clear:both;"></div>');

        pager.html(pagination.join(''));
    }

    /**
     * 绑定事件
     */
    function bindEvents(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target);

        $('a.x-pagination-first', pager).unbind('.pagination').bind('click.pagination', function() {
            if (opts.pageNumber > 1) {
                selectPage(target, 1);
            }
        });
        $('a.x-pagination-prev', pager).unbind('.pagination').bind('click.pagination', function() {
            if (opts.pageNumber > 1) {
                selectPage(target, opts.pageNumber - 1);
            }
        });
        $('a.x-pagination-next', pager).unbind('.pagination').bind('click.pagination', function() {
            var pageCount = Math.ceil(opts.total / opts.pageSize);
            if (opts.pageNumber < pageCount) {
                selectPage(target, opts.pageNumber + 1);
            }
        });
        $('a.x-pagination-last', pager).unbind('.pagination').bind('click.pagination', function() {
            var pageCount = Math.ceil(opts.total / opts.pageSize);
            if (opts.pageNumber < pageCount) {
                selectPage(target, pageCount);
            }
        });
        $('a.x-pagination-reload', pager).unbind('.pagination').bind('click.pagination', function() {
            selectPage(target, opts.pageNumber);
        });
        $('input.x-pagination-num', pager).unbind('.pagination').bind('keydown.pagination', function(e) {
            if (e.keyCode == 13) {
                var pageNumber = parseInt($(this).val()) || 1;
                selectPage(target, pageNumber);
            }
        });
        $('select.x-pagination-page-list', pager).unbind('.pagination').bind('change.pagination', function() {
            opts.pageSize = $(this).val();
            selectPage(target, opts.pageNumber);
        });
    }

    function selectPage(target, pageNumber) {
        var opts = $.data(target, 'pagination').options;
        var pageCount = Math.ceil(opts.total / opts.pageSize);
        if (pageNumber > pageCount) pageNumber = pageCount;
        if (pageNumber < 1) pageNumber = 1; //页码最小是1
        opts.onSelectPage.call(target, pageNumber, opts.pageSize);
        opts.pageNumber = pageNumber;
        showPagerInfo(target);
    }

    function showPagerInfo(target) {
        var opts = $.data(target, 'pagination').options;
        var pager = $(target);
        var pageCount = Math.ceil(opts.total / opts.pageSize);

        if (pageCount < 1) { //总页码数最小是1
            pageCount = 1;
        }
        $('input.x-pagination-num', pager).val(opts.pageNumber);
        $('span.x-pagination-after-page', pager).html(opts.afterPageText.replace(/{pages}/, pageCount));

        $('span.x-pagination-info', pager).html(opts.displayMsg.replace(/{total}/, opts.total));
        
        $('a.x-pagination-first,a.x-pagination-prev', pager).removeClass('x-pagination-btn-disabled').addClass((opts.pageNumber == 1) ? 'x-pagination-btn-disabled' : '');
        $('a.x-pagination-next,a.x-pagination-last', pager).removeClass('x-pagination-btn-disabled').addClass((opts.pageNumber == pageCount) ? 'x-pagination-btn-disabled' : '');
    }

    $.fn.pagination = function(options, param) {
        if (typeof options == 'string') {
            return $.fn.pagination.methods[options](this, param);
        }

        options = options || {};
        return this.each(function() {
            var state = $.data(this, 'pagination');
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.pagination.defaults, options);
                $.data(this, 'pagination', {
                    options: opts
                });
            }
            buildPagination(this);
            bindEvents(this);
            showPagerInfo(this);
        });
    };

    $.fn.pagination.methods = {
        options: function(jq) {
            return $.data(jq[0], "pagination").options;
        },
        select: function(jq, param) {
            return jq.each(function() {
                selectPage(this, param);
            });
        }
    };

    $.fn.pagination.parseOptions = function(target) {
        return $.extend({}, $.parser.parseOptions(target, []));
    };

    $.fn.pagination.defaults = {
        total: 0,
        pageSize: 10,
        pageNumber: 1,
        pageList: [10, 20, 50, 100],
        showPageList: true,
        showRefresh: true,
        beforePageText: '第',
        afterPageText: '共{pages}页',
        displayMsg: '共{total}条记录',
        onSelectPage: function(pageNumber, pageSize) {},
        onChangePageSize: function(pageSize) {}
    };
})(jQuery);
